<template>
  <div class="appointment-view">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">律师预约</h1>
      <p class="page-subtitle">填写预约信息，与专业律师进行咨询</p>
    </div>

    <div class="appointment-container">
      <!-- 律师信息卡片 -->
      <div class="lawyer-info-card" v-if="lawyerDetail">
        <div class="lawyer-header">
          <el-avatar :size="60" :src="lawyerDetail.avatarUrl" />
          <div class="lawyer-info">
            <h3>{{ lawyerDetail.realName }}</h3>
            <p>{{ lawyerDetail.barAssociation }}</p>
            <div class="rating">
              <el-rate
                :model-value="lawyerDetail.rating"
                disabled
                show-score
                text-color="#ff9900"
                score-template="{value} 分"
              />
            </div>
          </div>
          <div class="consultation-fee">
            <span class="fee-label">咨询费用</span>
            <span class="fee-amount">¥{{ lawyerDetail.hourRate }}/小时</span>
          </div>
        </div>

        <div class="specialty-tags">
          <el-tag
            v-for="specialty in lawyerDetail.specialties"
            :key="specialty"
            type="info"
            size="small"
          >
            {{ specialty }}
          </el-tag>
        </div>
      </div>

      <!-- 预约表单 -->
      <div class="appointment-form">
        <el-form
          ref="appointmentFormRef"
          :model="appointmentForm"
          :rules="appointmentRules"
          label-width="120px"
          class="demo-appointmentForm"
        >
          <el-form-item label="预约时间" prop="scheduledTime">
            <el-date-picker
              v-model="appointmentForm.scheduledTime"
              type="datetime"
              placeholder="选择预约时间"
              :disabled-date="disabledDate"
              :shortcuts="timeShortcuts"
              style="width: 100%"
            />
          </el-form-item>

          <el-form-item label="咨询时长" prop="duration">
            <el-radio-group v-model="appointmentForm.duration">
              <el-radio :label="30">30分钟</el-radio>
              <el-radio :label="60">60分钟</el-radio>
              <el-radio :label="90">90分钟</el-radio>
              <el-radio :label="120">120分钟</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="咨询方式" prop="appointmentType">
            <el-radio-group v-model="appointmentForm.appointmentType">
              <el-radio label="online">线上咨询</el-radio>
              <el-radio label="offline">线下咨询</el-radio>
              <el-radio label="other">其他</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="问题描述" prop="purpose">
            <el-input
              v-model="appointmentForm.purpose"
              type="textarea"
              :rows="4"
              placeholder="请详细描述您需要咨询的法律问题，包括相关背景、具体情况和期望达到的目标..."
              maxlength="500"
              show-word-limit
            />
          </el-form-item>

          <el-form-item label="相关文件" prop="files">
            <el-upload
              v-model:file-list="appointmentForm.files"
              action="#"
              multiple
              :auto-upload="false"
              :limit="5"
              :on-exceed="handleExceed"
              list-type="text"
            >
              <el-button type="primary" disabled>
                <el-icon><Upload /></el-icon>
                上传文件
              </el-button>
              <template #tip>
                <div class="el-upload__tip">支持上传图片、文档等文件，单个文件不超过10MB</div>
              </template>
            </el-upload>
          </el-form-item>

          <!-- 费用计算 -->
          <div class="fee-summary">
            <div class="fee-item">
              <span class="fee-label">咨询费用</span>
              <span class="fee-amount">¥{{ calculatedFee }}</span>
            </div>
            <div class="fee-total">
              <span class="total-label">总计</span>
              <span class="total-amount">¥{{ calculatedFee }}</span>
            </div>
          </div>

          <el-form-item>
            <el-button
              type="primary"
              :loading="submitting"
              @click="submitAppointment"
              class="submit-btn"
            >
              确认预约
            </el-button>
            <el-button @click="router.back()">返回</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, inject } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'
import { userInfoStore } from '@/stores/userinfo'

const router = useRouter()
const route = useRoute()
const api = inject('$api')
const userStore = userInfoStore()

// 响应式数据
const lawyerDetail = ref(null)
const submitting = ref(false)
const appointmentFormRef = ref()

// 预约表单数据
const appointmentForm = ref({
  lawyerId: null,
  scheduledTime: '',
  duration: 60,
  appointmentType: 'online',
  purpose: '',
  files: [],
})

// 表单验证规则
const appointmentRules = {
  scheduledTime: [{ required: true, message: '请选择预约时间', trigger: 'change' }],
  duration: [{ required: true, message: '请选择咨询时长', trigger: 'change' }],
  appointmentType: [{ required: true, message: '请选择咨询方式', trigger: 'change' }],
  purpose: [
    { required: true, message: '请输入咨询目的', trigger: 'blur' },
    { min: 10, message: '咨询目的至少10个字符', trigger: 'blur' },
  ],
}

// 时间快捷选项
const timeShortcuts = [
  {
    text: '1小时后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 1000)
      return date
    },
  },
  {
    text: '明天此时',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 24 * 1000)
      return date
    },
  },
  {
    text: '3天后',
    value: () => {
      const date = new Date()
      date.setTime(date.getTime() + 3600 * 24 * 3 * 1000)
      return date
    },
  },
]

// 计算费用
const calculatedFee = computed(() => {
  if (!lawyerDetail.value) return 0
  const hourlyRate = lawyerDetail.value.hourRate
  const hours = appointmentForm.value.duration / 60
  return Math.round(hourlyRate * hours * 100) / 100
})

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
}

// 文件上传处理
const handleExceed = () => {
  ElMessage.warning('最多只能上传5个文件')
}

// 获取律师详情
const fetchLawyerDetail = async (lawyerId) => {
  try {
    const response = await api.lawyers.getLawyerDetail(lawyerId)
    if (response.code === 200) {
      lawyerDetail.value = response.data
    } else {
      ElMessage.error('获取律师信息失败')
      router.back()
    }
  } catch (error) {
    console.error('获取律师详情失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    router.back()
  }
}

// 提交预约
const submitAppointment = async () => {
  if (!appointmentFormRef.value) return

  // 验证表单
  try {
    await appointmentFormRef.value.validate()
  } catch (error) {
    ElMessage.warning('请完善表单信息')
    return
  }

  // 检查用户是否登录
  if (!userStore || !userStore.isLoggedIn) {
    ElMessageBox.confirm('请先登录后再进行预约', '提示', {
      confirmButtonText: '去登录',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(() => {
      router.push('/login')
    })
    return
  }

  submitting.value = true

  try {
    const appointmentData = {
      lawyerId: appointmentForm.value.lawyerId,
      clientId: userStore.user.id,
      scheduledTime: appointmentForm.value.scheduledTime,
      duration: appointmentForm.value.duration,
      purpose: appointmentForm.value.purpose,
      type: appointmentForm.value.appointmentType,
      appointmentFee: calculatedFee.value,
    }

    // 调用预约接口
    const response = await api.appointment.createAppointment(appointmentData)

    if (response.code === 200) {
      ElMessage.success('预约成功！')
      // 跳转到我的预约页面或首页
      router.push('/')
    } else {
      ElMessage.error(response.message || '预约失败')
    }
  } catch (error) {
    console.error('预约失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  } finally {
    submitting.value = false
  }
}

onMounted(() => {
  const lawyerId = route.query.lawyerId
  if (lawyerId) {
    appointmentForm.value.lawyerId = lawyerId
    fetchLawyerDetail(lawyerId)
  } else {
    ElMessage.error('未选择律师')
    router.back()
  }
})
</script>

<style scoped>
.appointment-view {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-title {
  font-size: 2rem;
  color: #1a3a5f;
  margin: 15px 0 10px;
  font-weight: 700;
}

.page-subtitle {
  font-size: 1rem;
  color: #666;
}

.appointment-container {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  padding: 30px;
}

.lawyer-info-card {
  background: #f9fafb;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 30px;
  border-left: 4px solid #1a3a5f;
}

.lawyer-header {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.lawyer-info {
  flex: 1;
  margin-left: 15px;
}

.lawyer-info h3 {
  margin: 0 0 5px 0;
  color: #1a3a5f;
  font-size: 1.2rem;
}

.lawyer-info p {
  margin: 0 0 10px 0;
  color: #666;
}

.consultation-fee {
  text-align: right;
}

.fee-label {
  display: block;
  font-size: 0.9rem;
  color: #666;
  margin-bottom: 5px;
}

.fee-amount {
  font-size: 1.3rem;
  font-weight: 600;
  color: #ff6b35;
}

.specialty-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.appointment-form {
  margin-top: 20px;
}

.fee-summary {
  background: #f9fafb;
  border-radius: 8px;
  padding: 20px;
  margin: 20px 0;
}

.fee-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  color: #666;
}

.fee-total {
  display: flex;
  justify-content: space-between;
  padding-top: 10px;
  border-top: 1px solid #e0e0e0;
  font-weight: 600;
  color: #1a3a5f;
  font-size: 1.1rem;
}

.submit-btn {
  width: 200px;
  height: 45px;
  font-size: 1.1rem;
}
</style>
